package cn.magic.filter;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
* @Description: 自定义filter
* @Author: Mr.pc
* @Version: 1.0
* @Date:  2022/7/31 19:03
*/
@Component
public class CustomGatewayFilter implements GatewayFilter, Ordered {
    private static final Log log = LogFactory.getLog(GatewayFilter.class);
    private static final String COUNT_Start_TIME = "countStartTime";

    /*
    自定义filter
    1.实现GatewayFilter,Ordered
        1.1实现filter和getOrder方法
        1.2getOrder方法  就是返回一个int  排序用的  数字越小优先级越高
     */



    /** 
    * @Title: filter
    * @Description: 记录执行的时间
    * @Author: Mr.pc
    * @Version: 1.0
    * @Date:  2022/7/31 19:13  
    * @Parameters: [exchange, chain]
    * @Return reactor.core.publisher.Mono<java.lang.Void>
    */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //开始时间
        //exchange这个对象里面封装了http相关的参数
        exchange.getAttributes().put(COUNT_Start_TIME, System.currentTimeMillis());
        //执行完成之后
        return chain.filter(exchange).then(
                //Mono.fromRunnable(() -> 就是开了一个线程
                Mono.fromRunnable(() -> {
                    //开始时间
                    //exchange里面拿到一开始存的时间
                    Long startTime = exchange.getAttribute(COUNT_Start_TIME);
                    //结束时间
                    Long endTime=(System.currentTimeMillis() - startTime);
                    if (startTime != null) {
                        log.info("&&&&&&&&&&&&&&&&&&&&&&&");
                        log.info(exchange.getRequest().getURI().getRawPath() + ": " + endTime + "ms");
                    }
                })
        );

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
